<template>
  <div>
    <Field
      v-if="showType === 'edit'"
      :border="border"
      :name="name"
      :label="label"
      :labelWidth="labelWidth"
      :disabled="disabled"
      :rules="rules"
      :placeholder="placeholder"
      @click="showPicker = true"
      :value="currentValue | formatTime(formatValue)"
      :is-link="true"
      :readonly="true"
      :arrow-direction="arrow"
      ref="field"
    ></Field>
    <Field
      v-else-if="showType === 'view'"
      :border="border"
      :name="name"
      :readonly="true"
      :value="currentValue | formatTime(formatValue)"
      :label="label"
      :labelWidth="labelWidth"
    >
      <template #button>
        <slot></slot>
      </template>
    </Field>
    <!-- 弹窗 -->
    <van-popup v-model="showPicker" position="bottom">
      <van-datetime-picker
        v-model="pickerValue"
        @confirm="onConfirm"
        @cancel="showPicker = false"
        :type="pickerType"
        :default-index="defaultIndex"
        :min-date="minDate"
        :max-date="maxDate"
        :formatter="formatter"
      />
    </van-popup>
  </div>
</template>

<script>
import common from './item'
import { Popup as vanPopup, DatetimePicker as vanDatetimePicker } from 'vant'
import { formatTime } from './../tools'
export default {
  mixins: [common],
  components: {
    vanPopup,
    vanDatetimePicker
  },
  data () {
    return {
      showPicker: false,
      pickerValue: this.value,
      defaultIndex: 0,
      valueMap: {},
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2025, 10, 1)
    }
  },
  filters: {
    formatTime
  },
  computed: {
    // 计算表单显示格式的基数 YY/MM/DD
    formatValue () {
      let o = this.info
      let key = o.type
      let MAP = {
        date: 'YY/MM/DD',
        'year-month': 'YY/MM',
        'month-day': 'MM/DD',
        time: 'HH:MM',
        datetime: 'YY/MM/DD HH:MM:SS'
      }
      return o.formatValue || MAP[key]
    },
    // 弹窗的类型：date year-month month-day time datetime
    pickerType () {
      let o = this.info
      return o.type || ''
    },
    // 选项格式化函数
    formatter () {
      let o = this.info
      let fn = (type, val) => val
      return o.formatter || fn
    }
  },
  created () {
    let {
      minDate = new Date(2020, 0, 1),
      maxDate = new Date(2025, 10, 1)
    } = this.info
    this.minDate = minDate
    this.maxDate = maxDate
  },
  methods: {
    onConfirm (date) {
      this.currentValue = date
      this.$emit('change', date, this.name)
      this.showPicker = false
    }
  }
}
</script>
